package com.wkm.chainchain.deprecated_buildmock;

import com.wkm.chainchain.pbft.node.AllNodeInfo;
import com.wkm.chainchain.pbft.node.Node;
import com.wkm.chainchain.pbft.p2p.PBFTClient;
import com.wkm.chainchain.pbft.p2p.PBFTServer;
import com.wkm.chainchain.websocket.Client;

import java.util.concurrent.CountDownLatch;

public class MsgServer implements Runnable {

    private final CountDownLatch SERVER_NODE_LATCH;
    private final CountDownLatch NODE_CONNECTED_LATCH;
    private final int NODE_AMOUNT;
    private final int SERVER_PORT;

    private final int INDEX;

    public MsgServer(CountDownLatch serverNodeLatch, CountDownLatch nodeConnectedLatch, int NODE_AMOUNT, int SERVER_PORT, int index) {
        this.SERVER_NODE_LATCH = serverNodeLatch;
        this.NODE_CONNECTED_LATCH = nodeConnectedLatch;
        this.NODE_AMOUNT = NODE_AMOUNT;
        this.SERVER_PORT = SERVER_PORT;
        this.INDEX = index;
    }

    @Override
    public void run() {
        PBFTServer.getInstance(SERVER_PORT);
        //初始化当前节点
        Node node = Node.getInstance();
        node.setIndex(INDEX);
        node.setIp("127.0.0.1");
        node.setPort(SERVER_PORT);

        Node[] p2pNodeArrays = AllNodeInfo.P2P_NODE_ARRAYS;
        p2pNodeArrays[node.getIndex()] = node;

        SERVER_NODE_LATCH.countDown();

        // 所有服务端都已经打开的时候才往下执行
        try {
            SERVER_NODE_LATCH.await();
            System.out.println("所有的服务端已经打开，开始往下执行。");
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }

        Client client = PBFTClient.getInstance();
        //与消息发送客户端建立连接
        client.connectRequestClient();
        //初始化 连接所有的P2P节点
        for (int i = 0; i < NODE_AMOUNT; i++) {
            //与当前节点以外的节点建立连接
            if (node.getPort() == (SERVER_PORT - INDEX + i)) {
                continue;
            }
            client.connectPeer("ws://localhost:" + (SERVER_PORT - INDEX + i));
        }
        NODE_CONNECTED_LATCH.countDown();
    }
}
